import { uploadFileChunk } from "../../components/processFile.api";

export const calculateChunkHash = async (blob: Blob, algorithm: string = "SHA-256") => {
    const buffer = await blob.arrayBuffer();
    const hashBuffer = await crypto.subtle.digest(algorithm, buffer);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
    return hashHex;
};

const postChunk = async (
    blob: Blob,
    sessionID: string,
    algorithm: string = "SHA-256",
    hashHex: string,
    index: number
) => {
    const response = await uploadFileChunk(blob, sessionID, algorithm, hashHex, String(index));
    return response.success;
};
export const attemptChunkPost = async (
    blob: Blob,
    sessionID: string,
    algorithm: string = "SHA-256",
    hashHex: string,
    index: number
) => {
    const RETRY_COUNT = 5; // 重试次数
    // const TIMEOUT = 10000; //TODO 超时时间

    for (let i = 0; i < RETRY_COUNT; i++) {
        const success = await postChunk(blob, sessionID, algorithm, hashHex, index);
        if (!success) continue;
        return { success, sessionID, hashHex, index };
    }
    throw new Error(`Failed to post chunk index ${index} after ${RETRY_COUNT} retries`);
};
